package jogs.net.metaserver;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * ClientHandler inner class
 */

public class MSClientHandler extends Thread
{
  private Socket clientSocket; 
  private MetaServer metaServer;
  private BufferedReader in;
  private PrintStream out; 
  private boolean disconnected; 

  private String username; 

  public MSClientHandler(Socket _clientSocket, MetaServer _metaServer)
  {
    in = null;
    out = null; 
    clientSocket = _clientSocket; 
    metaServer = _metaServer; 
    disconnected = false; 
  }
  
  public String getUsername()
  {
  	return username;
  }
  
  public void send(String msg)
  {
    if (out != null) out.println(msg);
  }

  public boolean disconnected()
  {
  	return disconnected;
  }
  
  public void disconnect()
  {
  	try
  	{
  		metaServer.clientDisconnect(this);
  		out.close();
  		in.close();
  		clientSocket.close();
  	}
  	catch(Exception e)
  	{
  		
  	}
  }
  
  boolean handle(String line)
  {
    if (line.equals("#UPDATE_ROOM_INFO"))
      out.println("@OKROOMINFO:" + metaServer.getRoomInfo()); 
    else if (line.equals("#UPDATE_USER_LIST"))
      out.println("@OKUSERLIST:" + metaServer.getUserList()); 
    else if (line.startsWith("/join "))
    {
      System.out.println("Got room join request: " + line); 
      String info = metaServer.handleJoin(line, username); 
      if (info == null)
        System.out.println("handleJoin returned null"); 
      else
      {
        System.out.println("handleJoin succeeded, info=" + info); 
        out.println("@OKJOIN:" + info); 
      }
    }
    else if(line.startsWith("@DISC"))
    {
    	this.disconnected = true;
    	out.println("@OKDISCONNECT:");
    	disconnect();
    }
    else 
      return false; 
    
    return true; 
  }

  public void run()
  {
    try
    {
      in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
      out = new PrintStream(clientSocket.getOutputStream()); 

      boolean authenticated = false; 
      
      while (!authenticated)
      {
        out.println("AUTHENTICATE");
        String un = in.readLine(); 
        String pw = in.readLine(); 
        System.out.println("Read username and password. Authenticating via DB."); 
        authenticated = metaServer.authenticate(un, pw);
        username = un;  

        if (!authenticated)
          System.out.println("Auth failed with un:"+un+",pw:"+pw+"###"); 
      }

      out.println("LOGINSUCC"); 
      //out.println("USERS " + metaServer.getUserList());//tells new client who's already there.
      //metaServer.broadcast(username + " has entered the lobby.");
      metaServer.broadcast("@NEWUSER:" + username);

      String line = ""; 
      while (!disconnected && line != null)
      {
        line = in.readLine(); 
  
        boolean handled = handle(line); 

        if (!handled)
          metaServer.broadcast(username + ": " + line);  
      }
    }
    catch(Exception e)
    {
    	if(!disconnected)
    	{
    		System.out.println("Caught exception in client handler.. client stopping."); 
    		e.printStackTrace(); 
    		disconnected = true;  
    	}
    }
    disconnect();
  }
}
